<template>
  <div style="display:none"></div>
</template>

<style lang="scss">
.notify-bell {
  & > .el-notification__icon {
    color: #58a3f3;
  }
}
.notify-content {
  & > div span {
    word-wrap: break-word;
    word-break: break-all;
    overflow: hidden;
  }
  & > .notify-button {
    float: right;
  }
}
</style>

<script>

import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import { webSocketURL } from '@/utils/http'
import { getToken, getUser } from '@/utils/auth'
import { validatenull } from '@/utils/validate'

export default {
  data() {
    return {
      currentUser: validatenull(getUser()) ? null : JSON.parse(getUser()),
      stompClient: '',
      timer: ''
    }
  },
  methods: {
    gotoOrder(id) {
      this.$router.push({
        name: 'order',
        query: {
          orderId: id
        }
      })
    },
    gotoUser(id) {
      this.$router.push({
        name: 'user',
        query: {
          userId: id
        }
      })
    },
    openNotice(obj) {

    },
    initWebSocket() {
      if (validatenull(this.currentUser)) { return }
      this.connection()
      const that = this
      // 断开重连机制,尝试发送消息,捕获异常发生时重连
      this.timer = setInterval(() => {
        try {
          that.stompClient.send('test')
        } catch (err) {
          console.log('断线了: ' + err)
          that.connection()
        }
      }, 5000)
    },
    connection() {
      const socket = new SockJS(webSocketURL + 'notice-webSocket')
      this.stompClient = Stomp.over(socket)
      const headers = {
        'token': getToken(),
        'Content-Type': 'application/json;charset=UTF-8',
        'Access-Control-Allow-Origin': '*',
        'Accept': 'application/json'
      }
      this.stompClient.connect(headers, () => {
        this.stompClient.subscribe('/user/' + this.currentUser.userId + '/message', (response) => {
          let gotoFunc
          let id
          if (validatenull(response)) { return }
          const obj = JSON.parse(response.body)
          if (obj.type === 'order') {
            gotoFunc = this.gotoOrder
            id = obj.orderId
          } else if (obj.type === 'user') {
            gotoFunc = this.gotoUser
            id = obj.userId
          }
          const h = this.$createElement
          this.$notify({
            title: '新消息！',
            iconClass: 'el-icon-bell',
            customClass: 'notify-bell',
            showClose: true,
            dangerouslyUseHTMLString: true,
            message: h('div', {
              'class': 'notify-content'
            }, [
              h('div', null, [
                h('span', null, obj.msg)
              ]),
              h('div', {
                'class': 'notify-button'
              }, [
                h('el-button', {
                  attrs: {
                    size: 'mini',
                    type: 'primary',
                    plain: true
                  },
                  nativeOn: { click: () => { gotoFunc(id) } }
                }, '去审核')
              ])
            ]),
            offset: 100,
            duration: 0
          })
        })
      }, (err) => {
        console.log('失败')
        console.log(err)
      })
    },
    disconnect() {
      if (this.stompClient) {
        this.stompClient.disconnect()
      }
    }
  },
  mounted() {
    this.initWebSocket()
  },
  beforeDestroy: function() {
    console.log('离开页面')
    this.disconnect()
    clearInterval(this.timer)
  }
}
</script>
